package com.zheng.admin.validator;

import com.zheng.admin.form.LoginUser;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zcz on 2017/10/27.
 */
@Component
public class LoginUserValidator implements Validator {

    private Pattern PHONE_PATTERN = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$");

    @Override
    public boolean supports(Class<?> aClass) {
        return LoginUser.class.equals(aClass);
    }

    @Override
    public void validate(Object object, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "phone", "login.phone.empty", "手机号不能空");
        ValidationUtils.rejectIfEmpty(errors, "password", "login.password.empty", "密码不能为空");

        LoginUser loginUser = (LoginUser) object;
        Matcher matcher = PHONE_PATTERN.matcher(loginUser.getPhone());
        if (!matcher.find()) {
            errors.rejectValue("phone", "login.phone.wrong", "手机号不正确");
        }
    }
}
